package com.sgb.merchant.view.activity;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.link.entity.EventConstant;
import com.sgb.link.entity.MainEvent;
import com.sgb.link.entity.merchant.SelfProjectList;
import com.sgb.link.router.PathMerchant;
import com.sgb.link.view.widget.CustomXTabLayout;
import com.sgb.merchant.R;
import com.sgb.merchant.databinding.MerchantActivitySelfProjectListBinding;
import com.sgb.merchant.view.adapter.SelfInvestmentProjectAdapter;
import com.sgb.merchant.viewmodel.SelfProjectViewModel;
import com.swgk.core.base.model.entity.RouterKey;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick2;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 王彬臣
 * @date: 2021/8/12
 * @Description: 个人中心-招商投资项目列表
 */
@Route(path = PathMerchant.SelfProjectListActivity)
public class SelfProjectListActivity extends BaseActivity<SelfProjectViewModel, MerchantActivitySelfProjectListBinding> {
    private String[] titles = {"全部", "上架中", "已下架"};
    SelfInvestmentProjectAdapter mAdapter;
    private boolean mIsLoadMore;
    private boolean mIsHasSearch;
    Map<String, Object> mMap = new HashMap<>();
    int selectPos;

    @Override
    protected int layoutId() {
        return R.layout.merchant_activity_self_project_list;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(SelfProjectViewModel.class);

    }

    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        mBinding.setClick(this);
        initAdapter();
        for (String title : titles) {
            mBinding.tabIndustryCategory.addTab(mBinding.tabIndustryCategory.newTab().setText(title));
        }
        initEvent();
        initData();

    }

    private void initEvent() {
        mBinding.tabIndustryCategory.setNormalColor96();
        mBinding.tabIndustryCategory.addOnTabSelectedListener(new CustomXTabLayout.SimpleSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    mMap.remove("status");
                } else if (tab.getPosition() == 1) {//0 上架 1 下架
                    mMap.put("status", "0");
                } else if (tab.getPosition() == 2) {
                    mMap.put("status", "1");
                }
                DialogHelper.showProgressDialog(SelfProjectListActivity.this, "加载中...").setCanceledOnTouchOutside(true);
                refreshData(false);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        mBinding.ivCloseRed.setOnClickListener(v -> {
            mBinding.editSearchRed.setText("");
            if (mIsHasSearch) {
                DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
                closeKeybord();
                mMap.remove("itemName");
                refreshData(false);
            }
        });
        mBinding.editSearchRed.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mBinding.editSearchRed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                closeKeybord();
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mIsHasSearch = true;
                    if (TextUtils.isEmpty(mBinding.editSearchRed.getText().toString())) {
                        MToast.showToast(SelfProjectListActivity.this, "请输入项目名称");
                        return true;
                    }
                    DialogHelper.showProgressDialog(SelfProjectListActivity.this, "搜索中").setCanceledOnTouchOutside(true);
                    mMap.put("itemName", mBinding.editSearchRed.getText().toString());
                    refreshData(false);
                }
                return false;
            }
        });
        mBinding.editSearchRed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    mBinding.ivCloseRed.setVisibility(View.GONE);
                } else {
                    mBinding.ivCloseRed.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initData() {
        mViewModel.liveDataInvestment.observe(this, list -> showProjectList(list, mIsLoadMore));
        mViewModel.ldDel.observe(this, success -> {
            mAdapter.getDatas().remove(selectPos);
            mAdapter.notifyDataSetChanged();
            if(mAdapter.getDatas().size()==0){
                mBinding.displayView.setVisibility(View.GONE);
                mBinding.errorView.setVisibility(View.VISIBLE);
            }
        });
        mViewModel.ldStatus.observe(this,result->{
            if(!result){
                new RoundDialog.Builder(SelfProjectListActivity.this)
                        .title("温馨提示")
                        .content("该数据状态已发生变化，请刷新后再进行操作。")
                        .cancel("取消")
                        .confirm("确定")
                        .cancelable(false)
                        .confirmCallback(v12 -> refreshData(false)).show();
            }else{
                refreshData(false);
            }
        });
        mViewModel.ldState.observe(this, success -> {
            SelfProjectList entity = mAdapter.getDatas().get(selectPos);
            if (entity.getStatus().equals("0")) {
                entity.setStatus("1");
            } else {
                entity.setStatus("0");
            }
            mAdapter.notifyDataSetChanged();
        });
        getData();
    }

    private void refreshData(boolean b) {
        mIsLoadMore = b;
        getData();
    }

    private void initAdapter() {
        mBinding.displayView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SelfInvestmentProjectAdapter(this, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick2<SelfProjectList>() {
            @Override
            public void onItemClick(SelfProjectList investmentProjectEntity, int position) {
                ActivityJump.startActivity(PathMerchant.SelfInvestmentDetailActivity, Pair.create(RouterKey.NO, investmentProjectEntity.getNo()));
            }
        });
        mAdapter.setClickBtnListener(new SelfInvestmentProjectAdapter.ClickBtnListener() {

            @Override
            public void putAway(long no, int position) {
                selectPos = position;
                mViewModel.getDetailState(SelfProjectListActivity.this,no,1);
            }

            @Override
            public void dowAway(long no, int position) {
                selectPos = position;
               mViewModel.getDetailState(SelfProjectListActivity.this,no,2);
            }

            @Override
            public void editClick(long no, int position) {
                selectPos = position;
                mViewModel.getDetailState(SelfProjectListActivity.this,no,0);

            }

            @Override
            public void delClick(long no, int position) {
                selectPos = position;
                mViewModel.getDetailState(SelfProjectListActivity.this,no,3);

            }
        });
        mBinding.displayView.setAdapter(mAdapter);
        mBinding.refreshLayout.setEnableRefresh(true);
        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                refreshData(true);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData(false);
            }
        });
    }

    public void getData() {
        mViewModel.getInvestmentData(mIsLoadMore, mMap);
    }

    /**
     * 数据
     *
     * @param list
     * @param isLoadMore
     */
    public void showProjectList(List<SelfProjectList> list, boolean isLoadMore) {
        DialogHelper.dismissProgressDialog();
        mBinding.refreshLayout.finishRefresh();
        mBinding.refreshLayout.finishLoadMore();
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                mBinding.refreshLayout.resetNoMoreData();
                mAdapter.addDatas(list);
            } else {
                mBinding.refreshLayout.finishLoadMoreWithNoMoreData();
            }
            mBinding.displayView.setVisibility(View.VISIBLE);
        } else {
            if (null != list && list.size() > 0) {
                mBinding.displayView.setVisibility(View.VISIBLE);
                mBinding.errorView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.setDatas(null);
                mBinding.displayView.setVisibility(View.GONE);
                mBinding.errorView.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back_red) {
            finish();

        } else if (v.getId() == R.id.tv_search) {
            if (mBinding.editSearchRed.getText().toString().equals("")) {
                MToast.showToast(this, "请输入项目名称");
                return;
            }
            DialogHelper.showProgressDialog(this, "搜索中").setCanceledOnTouchOutside(true);
            mIsHasSearch = true;
            mMap.put("itemName", mBinding.editSearchRed.getText().toString());
            closeKeybord();
            refreshData(false);
        } else if (v.getId() == R.id.tv_publish) {
            ActivityJump.startActivity(PathMerchant.InvestmentPublishActivity);
        }
    }

    @Override
    public boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_MERCHANT_SELF_REFRESH) {
            refreshData(false);
        }
    }
}
